<template>
	<!--物资管理-直进直出-->
	<a-card :bordered="false">
		<!-- 查询区域 -->
		<div class="table-page-search-wrapper">
			<a-form layout="inline" @keyup.enter.native="searchQuery">
				<a-row :gutter="21">
					<a-col :xl="7" :md="10" :sm="12">
						<a-form-item label="时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
							<j-date v-model="queryParam.queryStartTime" :showTime="true" date-format="YYYY-MM-DD "
								style="width: 25%" placeholder="请选择开始时间"
								@change="tolink('queryStartTime',$event)"></j-date>
							<span style="width: 10px">~</span>
							<j-date v-model="queryParam.queryEndTime" :showTime="true" date-format="YYYY-MM-DD"
								style="width: 25%" placeholder="请选择结束时间"
								@change="tolink('queryEndTime',$event)"></j-date>
						</a-form-item>
					</a-col>
					<a-col :xl="5" :lg="9" :md="11" :sm="24">
						<a-form-item label="物资名称">
							<a-input placeholder="请输入物资名称" class="input1" v-model="queryParam.platformProductName"
								style="width: 100%;" @input="tolink('input_platformProductName',$event)"></a-input>
						</a-form-item>
					</a-col>
					<a-col :xl="5" :lg="9" :md="11" :sm="24">
						<a-form-item label="单号">
							<a-input placeholder="请输入单号" class="input1" v-model="queryParam.orderNo"
								style="width: 100%;" @input="tolink('input_orderNo',$event)"></a-input>
						</a-form-item>
					</a-col>
					<a-col :xl="5" :lg="8" :md="11" :sm="24">
						<a-form-item label="型号">
							<a-input placeholder="请输入型号" class="input1" v-model="queryParam.model" style="width: 100%;"
								@input="tolink('input_model',$event)"></a-input>
						</a-form-item>
					</a-col>
					<!-- <a-col :xl="5" :lg="8" :md="11" :sm="24">
              <a-form-item label="库房">
                <a-input  placeholder="请输入库房" class="input1" v-model="queryParam.warehouseName"></a-input>
              </a-form-item>
            </a-col> -->
					<a-col :xl="5" :lg="8" :md="11" :sm="24">
						<a-form-item label="项目">
							<!-- <a-select :options="levelOneOptions" placeholder="请输入项目" class="input1"
                v-model="queryParam.projectId"></a-select> -->
							<a-select placeholder="请输入项目" :value="queryParam.projectName"
								@change="handleChange('project',$event)">
								<a-select-option v-for="(item,index) in levelOneOptions" :key="index" :value="item">
									{{item.label}}
								</a-select-option>
							</a-select>
						</a-form-item>
					</a-col>
					<a-col :xl="5" :lg="9" :md="11" :sm="24">
						<a-form-item label="填单人">
							<a-input placeholder="请输入填单人" v-model="queryParam.userName"
								@input="tolink('input_userName',$event)"></a-input>
						</a-form-item>
					</a-col>
					<a-col :xl="5" :lg="9" :md="11" :sm="24">
						<a-form-item label="供应商">
							<a-input placeholder="请输入供应商" v-model="queryParam.supplierName"
								@input="tolink('input_supplierName',$event)"></a-input>
						</a-form-item>
					</a-col>
					<!-- <a-col :xl="5" :lg="8" :md="11" :sm="24">
              <a-form-item label="出入库选项">
                <a-select placeholder="请选择类型" v-model="queryParam.type">
                <a-select-option value="1">入库</a-select-option>
                <a-select-option value="2">出库</a-select-option>

              </a-select>
              </a-form-item>
            </a-col> -->

					<a-col :xl="4" :lg="6" :md="8" :sm="24">
						<span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
							<a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
							<a-button type="primary" @click="searchReset" icon="reload"
								style="margin-left: 8px">重置</a-button>
							<!--              <a @click="handleToggleSearch" style="margin-left: 8px">
                  {{ toggleSearchStatus ? '收起' : '展开' }}
                  <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
                </a>-->
						</span>
					</a-col>
				</a-row>
			</a-form>
		</div>
		<!-- 查询区域-END -->

		<!-- 操作按钮区域 -->
		<div class="table-operator">
			<a-button type="primary" icon="download" @click="handleExportXls('直进直出表')">导出</a-button>
		</div>

		<!-- table区域-begin -->
		<div>
			<!--      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
          <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
          <a style="margin-left: 24px" @click="onClearSelected">清空</a>
        </div>-->

			<a-table ref="table" size="middle" v-bind="tableProps" bordered rowKey="id" class="j-table-force-nowrap"
				:scroll="{x:true}" :columns="columns" :data-source="dataSource" :pagination="ipagination"
				:loading="loading" @change="handleTableChange">

				<template slot="htmlSlot" slot-scope="text">
					<div v-html="text"></div>
				</template>
				<template slot="imgSlot" slot-scope="text">
					<!-- <div v-for="(fileDetail, index) in treeData" :key="index">
            <div style="float: left; width: 104px; height: 104px; margin-right: 10px; margin: 0 8px 8px 0">
              <div
                style="
                  width:30px;
                  height: 45px;
                  position: relative;
                  padding: 8px;
                  border: 1px solid #d9d9d9;
                  border-radius: 4px;
                "
              >

                <img  :src="fileDetail.imgUrl" :preview="1" />
              </div>
            </div>
          </div> -->
					<span v-if="!text" style="font-size: 12px; font-style: italic">无图片</span>
					<img v-else :src="getImgView(text)" height="25px" alt="" preview="2"
						style="max-width: 80px; font-size: 12px; font-style: italic" />
				</template>
				<template slot="number" slot-scope="text,record">
					<span>{{text}}</span>
				</template>
				<template slot="fileSlot" slot-scope="text">
					<span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
					<a-button v-else :ghost="true" type="primary" icon="download" size="small"
						@click="downloadFile(text)">
						下载
					</a-button>
				</template>

				<!-- <template slot="imgUrl" slot-scope="text, record">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无图片</span>
          <imgs-preview v-else :imgs="text" imgH="25px"></imgs-preview>
        </template> -->

				<template slot="action" slot-scope="text, record">
					<a @click="handleEdits(record,'edit')">编辑</a>
					<a-divider type="vertical" />
					<a @click="handleDetails(record)">详情</a>
					<a-divider type="vertical" />
					<a @click="handleImgDetails(record)">查看图片</a>
					<a-divider type="vertical" />
					<a-popconfirm title="确定删除吗？" @confirm="handleDelete(record.id)">
						<a>删除</a>
					</a-popconfirm>
					
					<!-- <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                    <a> 删除</a>
                  </a-popconfirm> -->
					<!--          <a-divider type="vertical" />
            <a-dropdown>
              <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a @click="handleDetail(record)">详情</a>
                </a-menu-item>
                <a-menu-item>
                  <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                    <a>删除</a>
                  </a-popconfirm>
                </a-menu-item>
              </a-menu>
            </a-dropdown>-->
				</template>

			</a-table>
		</div>
		<wt-materials-detail-modal ref="modalForm" @ok="modalFormOk" />
		<wt-img-detail-modal ref="modalForm1" @ok="modalFormOk" />
	</a-card>
</template>

<script>
	import WtMaterialsDetailModal from './modules/WtMaterialsDetailModal'
	import WtImgDetailModal from './modules/WtImgDetailModal'
	import {
		JeecgListMixin
	} from '@/mixins/JeecgListMixin'

	import '@/assets/less/TableExpand.less'
	import {
		httpAction,
		getAction,
		postAction
	} from '@/api/manage'
	export default {
		name: "WtWuziList",
		mixins: [JeecgListMixin],
		components: {
			WtMaterialsDetailModal,
			WtImgDetailModal
		},
		data() {
			return {
				description: '物资明细',
				// 表头
				columns: [{
						// title: '#',
						width: '70px',
						align: 'center',
						dataIndex: 'rowIndex',
						customRender: function(text, r, index) {
							return (text !== '总计') ? (parseInt(index) + 1) : text
						}
					},
					{
						title: '时间',
						align: "center",
						dataIndex: 'createTime'
					},
					{
						title: '单号',
						align: "center",
						dataIndex: 'orderNo'
					},
					{
						title: '项目',
						align: "center",
						dataIndex: 'projectName'
					},
					{
						title: '物资名称',
						align: "center",
						dataIndex: 'platformProductName'
					},
					{
						title: '型号',
						align: "center",
						dataIndex: 'model'
					},
					{
						title: '用途',
						align: "center",
						dataIndex: 'purpose'
					},
					{
						title: '填单人',
						align: "center",
						dataIndex: 'userName',
					},
					{
						title: '领料人/领料班组',
						align: "center",
						dataIndex: 'materialHandler'
					},
					{
						title: '抽检磅数',
						align: "center",
						dataIndex: 'poundNum'
					},
					{
						title: '数量',
						align: "center",
						dataIndex: 'number',
					},
					{
						title: '单位',
						align: "center",
						dataIndex: 'unit',
					},
					/* {
					  title: '送料单/领料单照片',
					  align: "center",
					  dataIndex: 'imgUrl',
					  scopedSlots: {
					    customRender: 'imgUrl'
					  },
					}, */
					{
						title: '供应商',
						align: "center",
						dataIndex: 'supplierName',
					},
					{
						title: '操作',
						dataIndex: 'action',
						align: "center",
						width: 120,
						scopedSlots: {
							customRender: 'action'
						},
					}

					// {
					//   title:'图片',
					//   align:"center",
					//   dataIndex: 'imgUrl',
					//   scopedSlots: { customRender: 'imgSlot' },
					// },

					// {
					//   title:'单价',
					//   align:"center",
					//   dataIndex: 'price'
					// },
					// {
					//   title: '操作',
					//   dataIndex: 'action',
					//   align:"center",
					//   fixed:"right",
					//   width:147,
					//   scopedSlots: { customRender: 'action' },
					// }
				],
				url: {
					list: `/materials/wtMaterials/detail/list?type=${3}`,
					delete: '/materials/wtMaterials/deleteDetail',
					deleteBatch: "/materials/wtMaterials/deleteBatch",
					exportXlsUrl: "/materials/wtMaterials/ingress/exportXls",
					importExcelUrl: "materials/wtMaterials/importExcel",

				},
				ipagination: {
					current: 1,
					pageSize: 10,
					pageSizeOptions: ['10', '20', '30', '50', '100', '200', '300', '400', '500', '600', '700', '1000'],
					showTotal: (total, range) => {
						return range[0] + '-' + range[1] + ' 共' + total + '条'
					},
					showQuickJumper: true,
					showSizeChanger: true,
					total: 0,
				},
				dictOptions: {},
				newArr: [],
				levelOneOptions: [],
				treeData1: [],
				dataSource: [],
				newDataSource: [],
				footerDataSource: [],
				pageSwitch: true,
				superFieldList: [],
				is_localstorage: 'zjzc', //直进直出-搜索缓存
			}
		},
		created() {
			this.getSuperFieldList();
		},

		watch: {
			// update-begin---author:wangshuai ---date:20220209  for：[JTC-494]常用示例->表格合计写法改成新的写法------------
			// 'pageSwitch':function(val){
			//    if(!val){
			//      this.dataHandling('-1',0)
			//    }else{
			//      this.dataHandling(1,this.ipagination.pageSize)
			//    }
			// },
			// 'ipagination.current':function(val) {
			//   this.dataHandling(val,this.ipagination.pageSize)
			// },
			// // 当合计行变化时，绑定滚动条
			// 'footerDataSource': {
			//   async handler(dataSource) {
			//     // 当底部合计行有值，并且显示出来时，再同步滚动条
			//     if (dataSource && dataSource.length > 0) {
			//       await this.$nextTick()
			//       // 同步表与footer滚动
			//       let dom = this.$refs.table.$el.querySelectorAll('.ant-table-body')[0]
			//       let footerDom = this.$refs.footerTable.$el.querySelectorAll('.ant-table-body')[0]
			//       dom.addEventListener(
			//           'scroll',
			//           () => {
			//             footerDom.scrollLeft = dom.scrollLeft
			//           },
			//           true,
			//       )
			//     }
			//   },
			//   //update-end---author:wangshuai ---date:20220209  for：[JTC-494]常用示例->表格合计写法改成新的写法------------
			// }
		},
		computed: {
			// 数据表格的固定属性
			tableProps() {
				let tableProps = {
					size: 'middle',
					rowKey: 'rowIndex',
					columns: this.columns,
					scroll: {
						x: true
					},
				}
				let renderFooter = this.footerDataSource.length === 0 ? null : () => this.renderTableFooter(tableProps)
				return {
					...tableProps,
					ref: 'table',
					class: 'chart-data-list',
					pagination: this.pageSwitch ? this.ipagination : false,
					columns: this.columns,
					dataSource: this.dataSource,
					footer: renderFooter,
				}
			},
			pageSwitchProps() {
				return {
					checkedChildren: '分页',
					unCheckedChildren: '分页',
					style: {
						position: 'absolute',
						right: '0px',
						top: '-10px'
					}
				}
			},
		},
		mounted() {
			// this.tableAddTotalRow(this.columns, this.dataSource)
			/*新增分页合计方法*/
			this.newDataSource = this.dataSource


		},
		methods: {
			handleEdits(record,type){
				this.$refs.modalForm.title = '编辑';
				this.$refs.modalForm.pageType = type;
				this.$refs.modalForm.edit(record);
				this.$refs.modalForm.disableSubmit = false;
			},
			tolink(type, record) {
				if (!!this.is_localstorage) {
					localStorage.setItem(this.is_localstorage, JSON.stringify(this.queryParam));
				}
			},
			handleChange(type, item) {
				if (type === 'project') {
					this.queryParam.projectName = item.label;
					this.queryParam.projectId = item.value;
				} else if (type === 'type') {
					this.queryParam.typeName = item.label;
					this.queryParam.type = item.value;
				}
				this.$forceUpdate();
				if (!!this.is_localstorage) {
					localStorage.setItem(this.is_localstorage, JSON.stringify(this.queryParam));
				}
			},
			handleDetails(record) {
				this.$refs.modalForm.title = '详情';
				this.$refs.modalForm.pageType = 'detail';
				this.$refs.modalForm.edit(record);
				this.$refs.modalForm.disableSubmit = true;
			},
			handleImgDetails(record) {
				this.$refs.modalForm1.title = '图片详情';
				this.$refs.modalForm1.pageType = 'detail';
				this.$refs.modalForm1.edit(record);
				this.$refs.modalForm1.disableSubmit = true;
			},
			/** 表格增加合计行 */
			tableAddTotalRow(columns, dataSource) {
				let numKey = 'rowIndex'
				console.log('e11w', dataSource);
				let totalRow = {
					[numKey]: '总计'
				}
				columns.forEach(column => {
					let {
						key,
						dataIndex
					} = column
					if (![key, dataIndex].includes(numKey)) {

						let total = 0
						dataSource.forEach(data => {
							total += /^\d+\.?\d?$/.test(data[dataIndex]) ? Number.parseInt(data[
								dataIndex]) : Number.NaN
							console.log(data[dataIndex], ':', (/^\d+\.?\d?$/.test(data[dataIndex]) ? Number
								.parseInt(data[
									dataIndex]) : Number.NaN))
						})

						if (Number.isNaN(total)) {
							total = '-'
						}
						totalRow[dataIndex] = total
					}
				})

				dataSource.push(totalRow)
			},
			// handleTableChange(pagination, filters, sorter) {
			//   this.ipagination = pagination;
			// },
			//update-begin---author:wangshuai ---date:20220209  for：[JTC-494]常用示例->表格合计写法改成新的写法------------
			/*如果分页走这个方法*/
			async dataHandling(pageNo, pageSize, dataSource) {
				//根据当前页数和每页显示条数分割数组
				this.newDataSource = dataSource

				let arrs = [];
				//如果pageNo不是-1（不分页）,那么需要对数据进行分页计算
				if (pageNo != -1) {
					arrs = this.newDataSource.slice((pageNo - 1) * pageSize, pageNo * pageSize)
				} else {
					arrs = this.newDataSource
				}
				let newDataSource = [];
				let newArr = {};
				newArr.rowIndex = "总计"
				let number = 0;
				/* let point = 0;
				//每一项的数值相加
				for (let j = 0; j < arrs.length; j++) {
				  let Number1 = Number(arrs[j].number)
				  number += Number1;
				} */
				let params = JSON.parse(JSON.stringify(this.queryParam));
				params.type = '3';
				let resdata = await getAction('/materials/wtMaterials/getStatisticsWtMaterialsDetail', params);
				console.log(2333, resdata)
				if (resdata.success) {
					number = resdata.result.residueCount;
				}
				newArr.number = number.toFixed(3);

				// newArr.point=point;
				newDataSource.push(newArr);
				//给foot底部数组赋值
				this.footerDataSource = newDataSource;
			},
			// 渲染表格底部合计行
			renderTableFooter(tableProps) {
				let h = this.$createElement
				return h('a-table', {
					ref: 'footerTable',
					props: {
						...tableProps,
						pagination: false,
						dataSource: this.footerDataSource,
						showHeader: false,
					},
				})
				//update-end---author:wangshuai ---date:20220209  for：[JTC-494]常用示例->表格合计写法改成新的写法------------
			},
			loadData(arg) {
				// if(!this.url.list){
				//   this.$message.error("请设置url.list属性!")
				//   return
				// }
				//加载数据 若传入参数1则加载第一页的内容
				if (arg === 1) {
					this.ipagination.current = 1;
				}
				var params = this.getQueryParams(); //查询条件
				this.loading = true;
				getAction(this.url.list, params).then((res) => {

					if (res.success) {
						//update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
						this.dataSource = res.result.records || res.result;

						if (res.result.total) {
							this.ipagination.total = res.result.total;
						} else {
							this.ipagination.total = 0;
						}
						this.dataHandling(1, this.ipagination.pageSize, this.dataSource)
						//update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
					} else {
						this.$message.warning(res.message)
					}
				}).finally(() => {
					this.loading = false
				})
				getAction(`/sys/sysDepart/getDepartByOrgType?orgType=1`).then((res) => {
					if (res.success) {

						this.treeData1 = []
						let treeList1 = res.result
						for (let a = 0; a < treeList1.length; a++) {
							let temp = treeList1[a]
							temp.isLeaf = temp.leaf
							this.treeData1.push(temp)
						}

						this.levelOneOptions = [...this.treeData1].map((v) => {
							return {
								...v,
								value: v.id,
								label: v.departName,
							}
						})


					}
				})

			},
			initDictConfig() {},
			getSuperFieldList() {
				let fieldList = [];
				fieldList.push({
					type: 'string',
					value: 'name',
					text: '物资名称',
					dictCode: ''
				})
				fieldList.push({
					type: 'string',
					value: 'model',
					text: '型号',
					dictCode: ''
				})
				fieldList.push({
					type: 'string',
					value: 'number',
					text: '数量',
					dictCode: ''
				})
				fieldList.push({
					type: 'string',
					value: 'warehouseName',
					text: '仓库',
					dictCode: ''
				})
				fieldList.push({
					type: 'string',
					value: 'createTime',
					text: '时间',
					dictCode: ''
				})
				fieldList.push({
					type: 'string',
					value: 'type_dictText',
					text: '出库入库选项',
					dictCode: ''
				})


				this.superFieldList = fieldList
			}
		}
	}
</script>
<style scoped>
	@import '~@assets/less/common.less';

	.input1 {
		width: 170px;
		height: 30px;
	}
</style>